//
//  MoreActionsViewController.m
//  reacticons
//
//  Created by Nong Nghia on 4/24/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MoreActionsViewController.h"
#import "ButtonView.h"
#import "AboutUsViewController.h"
#import "HelpViewController.h"
#import <FacebookSDK/FacebookSDK.h>
#import "CMCFBShareViewController.h"
#import "Utilities.h"
#import "DatabaseConnection.h"
#import "Photo.h"
@interface MoreActionsViewController ()

@end

static NSArray *imageNameArray;
static NSArray *textArray;

@implementation MoreActionsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title=@"More";

        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    imageNameArray=[[NSArray alloc] initWithObjects:
                @"More_AboutUs.png",
                @"More_Help.png",
                @"More_RateUs.png",
                @"More_Contact.png",
                @"More_recommend.png",
                @"More_facebook.png",
                @"More_twitter.png",
                @"More_Setting.png",
                nil];
    textArray=[[NSArray alloc] initWithObjects:
                @"About Us",
                @"Help",
                @"Rate Us in the app store!",
                @"Contact/Submit your pics!",
                @"Recommend This App",
                @"Share us on Facebook",
                @"tweet tweet tweet!",
                @"Clear cache",
                nil];
    
//    [_tableView setScrollEnabled:NO];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - UITableView DataSource & Delegate


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [textArray count];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell =[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MoreCellIdentifier"] autorelease];
    UIImageView *imageView=[[UIImageView alloc] initWithFrame:CGRectMake(5, 5, 30, 30)];
    [imageView setImage:[UIImage imageNamed:[imageNameArray objectAtIndex:indexPath.row]]];
    [imageView setFrame:CGRectMake(5, 5, 30, 30)];
    [imageView setContentMode:UIViewContentModeScaleAspectFit];
    [cell.contentView addSubview:imageView];
    [imageView release];
    
    UILabel *textLabel =[[UILabel alloc] initWithFrame:CGRectMake(45, 10, 200, 20)];
    [textLabel setText:[textArray objectAtIndex:indexPath.row]];

    [textLabel setFont:[UIFont boldSystemFontOfSize:15]];
    [cell addSubview:textLabel];
    
    [textLabel release];
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row==0) {
        AboutUsViewController *auVC=[[AboutUsViewController alloc] init];
        [self.navigationController pushViewController:auVC animated:YES];
        [auVC release];
    }
    else if (indexPath.row==1){
        HelpViewController *hVC=[[HelpViewController alloc] init];
        [self.navigationController pushViewController:hVC animated:YES];
        [hVC release];
    }
    else if (indexPath.row==2){
        NSURL *url=[NSURL URLWithString:@"itms-apps://itunes.com/apps/reacticons"];
        [[UIApplication sharedApplication] openURL:url];
    }
    else if (indexPath.row==3){
        //contact
        [self sendMailTo:@"reacticons@gmail.com" WithSubject:nil andBody:@"<br/>(if submitting a pic, remember to paste it in this email!)" andLinkURL:nil];
    }

    else if (indexPath.row==4){
        
        //recommend
        [self sendMailTo:nil  WithSubject:@"Check out this app!" andBody:@"Check out this hilarious app of reaction images for your texts!" andLinkURL:@"http://itunes.com/apps/reacticons"];

    }

    else if (indexPath.row==5){
        //share fb
        CMCFBShareViewController *cfsVC=[[CMCFBShareViewController alloc] init];
        [cfsVC setImage:[UIImage imageNamed:@"Icon114.png"]];
        [cfsVC setText:@"Check out this hilarious app of reaction images for your texts!\nhttp://itunes.com/apps/reacticons"];
        [CMCFBShareViewController presentViewController:cfsVC];
        
    }
    else if (indexPath.row==6){
        //share twitter
        
        if ([TWTweetComposeViewController canSendTweet]) {
            TWTweetComposeViewController *tweet=[[TWTweetComposeViewController alloc] init];
            [tweet setInitialText:@"Check out this hilarious app of reaction images for your texts"];
            [tweet addURL:[NSURL URLWithString:@"http://itunes.com/apps/reacticons"]];
            [tweet addImage:[UIImage imageNamed:@"Icon114.png"]];
            [tweet setCompletionHandler:^(TWTweetComposeViewControllerResult result){
                [self dismissModalViewControllerAnimated:YES];
                switch (result) {
                    case TWTweetComposeViewControllerResultDone:
                        DBLOG(@"Done");
                        break;
                    case TWTweetComposeViewControllerResultCancelled:
                        DBLOG(@"Cancel");
                        break;
                    default:
                        break;
                }
                
            }];
            [self presentModalViewController:tweet animated:YES];
            [tweet release];
        }
        else{
            UIAlertView *alert =[[UIAlertView alloc]
                                 initWithTitle:@"  "
                                       message:@"Please login to Twitter Account in Setting or in Twitter Application before sharing!"
                                      delegate:nil
                             cancelButtonTitle:@"OK"
                             otherButtonTitles:  nil];
            [alert show];
            [alert release];
        }
    }
    else if (indexPath.row==7){
        NSString *documentPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"UPDATING_DATA"] isEqualToString:@"YES"]) {
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Cached Data"
                                                          message:[NSString stringWithFormat:@"Total amount used: %3.1f MB\nList is updating! Cannot clear now!",[Utilities sizeOfDirectory:documentPath]/(1024.0*1024.0)]
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles: nil];
            [alert show];
            [alert release];
            return;
        }
        
        
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Cached Data"
                                                      message:[NSString stringWithFormat:@"Total amount used: %3.1f MB\nClear cached images?",[Utilities sizeOfDirectory:documentPath]/(1024.0*1024.0)]
                                                     delegate:self
                                            cancelButtonTitle:@"CANCEL"
                                            otherButtonTitles:@"OK", nil];
        [alert setTag:10];
        [alert show];
        [alert release];
        return;
    }


}
#pragma mark - alert view delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ([alertView tag]==10) {
        if (buttonIndex==1) {
            NSString *documentFolder=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
            NSArray *fileList=[[NSFileManager defaultManager] subpathsAtPath:documentFolder];
            for (NSString *fileName in fileList) {
                BOOL isDirectory=NO;
                
                fileName=[fileName lastPathComponent];
                
                if ([[NSFileManager defaultManager] fileExistsAtPath:[documentFolder stringByAppendingPathComponent:fileName]
                                                         isDirectory:&isDirectory]) {
                    
                    if (!isDirectory){
                        if([[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] isEqualToString:@"plist"]||
                           [[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] isEqualToString:@"jpg"]||
                           
                           [[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] isEqualToString:@"png"]) {
                            DBLOG(@"remove:%@",fileName);
                            [[NSFileManager defaultManager] removeItemAtPath:[documentFolder stringByAppendingPathComponent:fileName] error:nil];
                            
                        }
                    }
                    
                }
            }
            
            NSArray *recentlyAddedList=[[NSFileManager defaultManager] subpathsAtPath:[documentFolder stringByAppendingPathComponent:@"TagThumbnail"]];
            for (NSString *fileName in recentlyAddedList) {
                BOOL isDirectory=NO;
                
                fileName=[fileName lastPathComponent];
                
                if ([[NSFileManager defaultManager] fileExistsAtPath:[[documentFolder stringByAppendingPathComponent:@"TagThumbnail"] stringByAppendingPathComponent:fileName]
                                                         isDirectory:&isDirectory]) {
                    
                    if (!isDirectory){
                        if([[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] isEqualToString:@"plist"]||
                           [[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] isEqualToString:@"jpg"]||
                           
                           [[[fileName componentsSeparatedByString:@"."] objectAtIndex:1] isEqualToString:@"png"]) {
                            //                            DBLOG(@"remove:%@",fileName);
                            [[NSFileManager defaultManager] removeItemAtPath:[[documentFolder stringByAppendingPathComponent:@"TagThumbnail"] stringByAppendingPathComponent:fileName] error:nil];
                            
                        }
                    }
                    
                }
            }
            
            NSMutableArray *arr=[[DatabaseConnection getRecentlyUsedPhotos] retain];
            for (Photo *item in arr) {
                [item setPhotoRecentlyUsed:@"19990102030405"];
                [DatabaseConnection writeListItems:[NSMutableArray arrayWithObject:[item itemObject]] toEntity:@"ManagedTumblrPhoto" withPrimaryKey:@"photoID"];
            }
            [arr release];
            
        }
        [[NSUserDefaults standardUserDefaults] setValue:@"UPDATE_SUCCESS" forKey:@"LIST_UPDATING"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}


#pragma mark - Send Mail

-(void)sendMailTo:(NSString*)_receiver
      WithSubject:(NSString*)_subject
          andBody:(NSString*)_body
       andLinkURL:(NSString*)_url
{
    
    if ([MFMailComposeViewController canSendMail]) {
        
        // Fill out the email body text
        //Create a string with HTML formatting for the email body

        MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
        emailDialog.mailComposeDelegate = self;
        if (_subject) {
            [emailDialog setSubject:_subject];

        }
        if (_body) {
            NSMutableString *emailBody = [[[NSMutableString alloc] initWithString:@"<html><body>"] retain];
            //Add some text to it however you want
            [emailBody appendString:[NSString stringWithFormat:@"<p>%@</p>",_body]];
            if (_url) {
                [emailBody appendString:[NSString stringWithFormat:@"<a href='%@'>%@</a>",_url,_url]];
            }
            [emailBody appendString:@"</body></html>"];
            [emailDialog setMessageBody:emailBody isHTML:YES];
            [emailBody release];


        }
        
        if (_receiver) {
            [emailDialog setToRecipients:[NSArray arrayWithObject:_receiver]];
        }
        [self presentModalViewController:emailDialog animated:YES];
        [emailDialog release];
    }
    else {
        
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Cannot Send Via Mail" message:@"Please setup your mail before share via Email" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    

    
}
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    [self dismissModalViewControllerAnimated:YES];

    
}



@end
